package com.andrew.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.andrew.dao.impl.BookDaoImpl;
import com.andrew.dao.impl.CartDaoImpl;
import com.andrew.entity.Book;
import com.andrew.entity.Cart;
import com.andrew.entity.CartDetail;
import com.andrew.entity.CartDetailBean;
import com.andrew.entity.Customer;
import com.andrew.service.CartService;
import com.sun.org.apache.xerces.internal.xs.XSIDCDefinition;


public class CartServiceImpl implements CartService {
	private CartDaoImpl cdi=new CartDaoImpl();
	private BookDaoImpl bdi=new BookDaoImpl();
	@Override
	public Cart getCart(int customerId) throws SQLException {
		// TODO Auto-generated method stub
		
		return cdi.queryCart(customerId);
	}



	
	/***
	 * 添加购物车信息
	 */
	@Override
	public String addCart(int bookId,int quantity ,Cart cart) throws SQLException {
		// TODO Auto-generated method stub
		//judge the good has already added?
		CartDetail cd = cdi.queryCartDetailByBookIdAndCartId(bookId, cart);
			if(cd!=null) {
				//在购物车中修改以及加入购物车的数量
				int udateQuantity = cdi.udateQuantity(1, bookId, cart);
				if(udateQuantity>0) {
					return "success";
				}else {
					return "fail";
				}
			}else {
				int result=cdi.addCartDetailInfo(bookId, quantity, cart);
				if(result>0) {
					return "success";
				}else {
					return "fail";
				}
			}
	}
			
	/***
	 *	更改数量
	 */
	@Override
	public String updateQuantity(int service,int bookId,Cart cart)throws SQLException {
		
		//return changed rows for add or reduce the quantity of goods
		int result=cdi.udateQuantity(service, bookId, cart);
		if(result>0) {
			return cdi.queryCartDetailQuantity(bookId, cart);
		}else {
			
			return "false";
		}
		
		
	}





	@Override
	public List<CartDetailBean> queryCartDetail(Cart cart) throws SQLException {
		List<CartDetailBean> beanList=new ArrayList<CartDetailBean>();
		
		List<CartDetail> carDetailList = cdi.queryCartDetail(cart);
		for (CartDetail cartDetail : carDetailList) {
			CartDetailBean cartDetailBean=new CartDetailBean();
			Book book=bdi.queryBookbyBookId(cartDetail.getBookId());
			if(book.getStock()>0) {
				cartDetailBean.setQuantity(cartDetail.getQuantity());
				cartDetailBean.setPrice( book.getPrice().multiply(new BigDecimal(cartDetail.getQuantity())));
				cartDetailBean.setBook(book);	
				beanList.add(cartDetailBean);
			}

		}
		
		return beanList;
		
	}





	@Override
	public void clearCart(Customer customer) throws SQLException {
		// TODO Auto-generated method stub
		cdi.deleteByCustomerId(customer);
	}





	@Override
	public long countGoodsInCart(Cart cart) throws SQLException {
		return cdi.countCartDetailsByCart(cart);
	}




	@Override
	public int deleteoneCartDetail(int bookId, Cart cart) throws SQLException {
		// TODO Auto-generated method stub
		return cdi.deleteOneCartDetail(bookId, cart);
	}







}
